package com.lyl.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lyl.dto.LogisticalDTO;
import com.lyl.utils.LogisticalHttpUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author lyl
 * @created 2025/10/8 19:37
 * @description
 *
 */
@RestController
@RequestMapping("/logistical")
@SuppressWarnings("all")
public class LogisticalController {

    @PostMapping
    public Map<String, Object> getLogistical(@RequestBody LogisticalDTO logisticalDTO) {
        String host = "https://kzexpress.market.alicloudapi.com";
        String path = "/api-mall/api/express/query";
        String method = "POST";
        String appcode = "f8fba0a78bff46c49a5ec871e5e74521";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("expressNo", logisticalDTO.getExpressNo());
        bodys.put("mobile", logisticalDTO.getMobile());
        try {
            HttpResponse response = LogisticalHttpUtils.doPost(host, path, method, headers, querys, bodys);
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> resultMap = objectMapper.readValue(EntityUtils.toString(response.getEntity()), Map.class);
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("success", 500);
            errorResult.put("msg", "获取物流数据失败: " + e.getMessage());
            errorResult.put("code", 500);
            return errorResult;
        }
    }

}
